# -*- coding: utf-8 -*-
"""
LLM Provider适配器
"""

import json
import urllib.request
import urllib.error
from typing import Any, Dict, Optional


class LLMProvider:
    """LLM Provider基类"""

    def __init__(self, api_key: str, api_base: str = "", model: str = ""):
        """
        初始化Provider

        Args:
            api_key: API Key
            api_base: API Base URL
            model: 模型名称
        """
        self.api_key = api_key
        self.api_base = api_base
        self.model = model

    def chat(self, messages: list, temperature: float = 0.2) -> Optional[str]:
        """
        发送聊天请求

        Args:
            messages: 消息列表
            temperature: 温度

        Returns:
            响应内容
        """
        raise NotImplementedError


class DeepSeekProvider(LLMProvider):
    """DeepSeek Provider"""

    def __init__(self, api_key: str, model: str = "deepseek-chat"):
        super().__init__(api_key, "https://api.deepseek.com", model)

    def chat(self, messages: list, temperature: float = 0.2) -> Optional[str]:
        """DeepSeek聊天请求"""
        url = f"{self.api_base}/v1/chat/completions"
        payload = {
            "model": self.model,
            "messages": messages,
            "temperature": temperature,
        }
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}",
        }

        try:
            data = json.dumps(payload).encode("utf-8")
            req = urllib.request.Request(url, data=data, headers=headers, method="POST")
            with urllib.request.urlopen(req, timeout=120) as resp:
                body = resp.read().decode("utf-8", errors="ignore")
                result = json.loads(body)
                return result.get("choices", [{}])[0].get("message", {}).get("content")
        except Exception as e:
            print(f"DeepSeek API error: {e}")
            return None


class MinimaxProvider(LLMProvider):
    """Minimax Provider"""

    def chat(self, messages: list, temperature: float = 0.2) -> Optional[str]:
        """Minimax聊天请求"""
        if not self.api_base:
            return None

        url = f"{self.api_base}/v1/chat/completions"
        payload = {
            "model": self.model or "minimax-m2",
            "messages": messages,
            "temperature": temperature,
        }
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}",
        }

        try:
            data = json.dumps(payload).encode("utf-8")
            req = urllib.request.Request(url, data=data, headers=headers, method="POST")
            with urllib.request.urlopen(req, timeout=120) as resp:
                body = resp.read().decode("utf-8", errors="ignore")
                result = json.loads(body)
                return result.get("choices", [{}])[0].get("message", {}).get("content")
        except Exception as e:
            print(f"Minimax API error: {e}")
            return None


class GeminiProvider(LLMProvider):
    """Gemini Provider"""

    def chat(self, messages: list, temperature: float = 0.2) -> Optional[str]:
        """Gemini聊天请求"""
        if not self.api_base:
            return None

        url = f"{self.api_base}/v1/chat/completions"
        payload = {
            "model": self.model or "gpt-4o",
            "messages": messages,
            "temperature": temperature,
        }
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}",
        }

        try:
            data = json.dumps(payload).encode("utf-8")
            req = urllib.request.Request(url, data=data, headers=headers, method="POST")
            with urllib.request.urlopen(req, timeout=120) as resp:
                body = resp.read().decode("utf-8", errors="ignore")
                result = json.loads(body)
                return result.get("choices", [{}])[0].get("message", {}).get("content")
        except Exception as e:
            print(f"Gemini API error: {e}")
            return None
